package com.hengshan.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.hengshan.common.ResultBody;
import com.hengshan.common.annotation.SystemLog;
import com.hengshan.common.enums.BusinessType;
import com.hengshan.common.enums.ReturnCode;
import com.hengshan.common.utils.SecurityUtils;
import com.hengshan.domain.entity.Role;
import com.hengshan.domain.entity.User;
import com.hengshan.domain.vo.UserInfoVo;
import com.hengshan.exception.SystemException;
import com.hengshan.service.impl.RoleServiceImpl;
import com.hengshan.service.impl.UploadService;
import com.hengshan.service.impl.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 个人中心
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user/profile")
public class UserProfileController {

    private final UserServiceImpl userService;
    private final RoleServiceImpl roleService;
    private final UploadService uploadService;
    private final PasswordEncoder passwordEncoder;
    private final ServerProperties serverProperties;

    public static final String MODULE_NAME = "个人中心";
    public static final String[] IMAGE_EXTENSION = {"gif", "jpg", "jpeg", "png"};

    /**
     * 查看个人信息
     */
    @GetMapping
    public UserInfoVo profile() {
        User user = SecurityUtils.getUser();
        UserInfoVo userInfoVo = userService.getOneById(user.getId());
        List<Role> roles = roleService.selectRolesByUser(user);
        userInfoVo.setRoles(roles);
        return userInfoVo;
    }

    /**
     * 修改个人基本信息
     */
    @SystemLog(title = MODULE_NAME, businessType = BusinessType.UPDATE)
    @PostMapping
    public int updateProfile(@RequestBody User user) {
        Long userId = SecurityUtils.getUser().getId();
        user.setId(userId);
        return userService.updateUserProfile(user);
    }

    /**
     * 修改密码
     *
     * @param newPassword 新密码
     * @param oldPassword 旧密码
     */
    @SystemLog(title = MODULE_NAME, businessType = BusinessType.UPDATE)
    @PostMapping("/updatePwd")
    public ResultBody updatePwd(String oldPassword, String newPassword) {
        User user = userService.getById(SecurityUtils.getUser().getId());
        String password = user.getPassword();
        if (passwordEncoder.matches(oldPassword, password)) {
            return ResultBody.fail("修改密码失败，旧密码错误");
        }
        if (passwordEncoder.matches(newPassword, password)) {
            return ResultBody.fail("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(user.getId(), newPassword) > 0) {
            return ResultBody.success();
        }
        return ResultBody.fail("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     *
     * @param avatarfile 用户头像
     */
    @PostMapping(value = "/avatar")
    public ResultBody avatar(@RequestParam("avatarfile") MultipartFile avatarfile) {
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!ArrayUtil.containsIgnoreCase(IMAGE_EXTENSION, extension)) {
                throw new SystemException(ReturnCode.FILE_TYPE_ERROR);
            }
            String avatarURL = uploadService.saveLocal(avatarfile);
            // 更新数据库图片地址,同时返回新图片地址
            if (userService.updateUserAvatar(SecurityUtils.getUser().getId(), avatarURL)) {
                String url = "http://localhost:" + serverProperties.getPort() + "/images/" + avatarURL;
                return ResultBody.success(url);
            }
        }
        return ResultBody.fail("上传图片异常，请联系管理员");
    }
}
